package com.hdax.dm.Interceptor;

import com.alibaba.fastjson.JSON;
import com.hdax.dm.utils.Token.TokenUtil;
import com.hdax.dm.utils.response.CommonResponse;
import com.hdax.dm.utils.response.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /*@Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion方法在控制器的处理请求方法执行完成后执行，即视图渲染结束之后执行");
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle方法在控制器的处理请求方法调用之后，解析视图之前执行");
    }*/

    /**
     * preHandle方法在控制器的处理请求方法调用之前执行
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //是否需要鉴权
        if (request.getRequestURI().contains("/p/")) {
            //获取请求中的token
            String token= request.getHeader("token");
            try {
                String id= TokenUtil.parseToken(token);
                //从redis获取token，如果无法获取那就是token过期了
                String redisToken= redisTemplate.opsForValue().get("token:"+id);
                if (redisToken==null){
                    response.setContentType("application/json;charset=UTF-8");
                    PrintWriter out= response.getWriter();
                    CommonResponse commonResponse= ResponseUtil.returnFail("9999","登录超时！请重新登录");
                    out.println(JSON.toJSONString(commonResponse));
                    return false;
                }
                return true;
            }catch (Exception e){
                response.setContentType("application/json;charset=UTF-8");
                PrintWriter out= response.getWriter();
                CommonResponse commonResponse= ResponseUtil.returnFail("9999","验签失败！请重新登录");
                out.println(JSON.toJSONString(commonResponse));
                return false;
            }
        }else {
            return true;
        }
    }
}
